import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_ume/utils/toast_utils.dart';
import 'sp_util.dart';
import 'package:flutter_ume/res/shared_preferences_keys.dart';

var dio = new Dio();

class NetUtils {
  static Future getNoHead(String url, {Map<String, dynamic> params}) async {
    dio.options.contentType =
        ContentType.parse("application/x-www-form-urlencoded");

    var response = await dio.get(url, queryParameters: params);

    if (response.statusCode == 200) {
      return response.data;
    } else {
      ToastUtil.showShortToast('后端接口出现异常，请检测代码和服务器情况........');
      throw Exception('后端接口出现异常，请检测代码和服务器情况.........');
    }
  }

  static Future postNoHead(String url, {Map<String, dynamic> params}) async {
    dio.options.contentType =
        ContentType.parse("application/x-www-form-urlencoded");

    var response = await dio.post(url, queryParameters: params);
    print("response:$response");
    print("response.data:${response.data}");

    if (response.statusCode == 200) {
      return response;
    } else {
      ToastUtil.showShortToast('后端接口出现异常，请检测代码和服务器情况........');
      throw Exception('后端接口出现异常，请检测代码和服务器情况.........');
    }
  }

  static Future getWithToken(String url, {Map<String, dynamic> params}) async {
    dio.options.contentType =
        ContentType.parse("application/x-www-form-urlencoded");

    print('token:${SpUtil.getString(SpKeys.userToken)}');
    dio.options.headers['borrower-auth-token'] = SpUtil.getString(SpKeys.userToken);

    var response = await dio.get(url, queryParameters: params);

    if (response.statusCode == 200) {
      return response;
    } else {
      ToastUtil.showShortToast('后端接口出现异常，请检测代码和服务器情况........');
      throw Exception('后端接口出现异常，请检测代码和服务器情况.........');
    }
  }
}
